package org.example.Controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.example.Entity.Category;
import org.example.Entity.Setmeal;
import org.example.common.R;
import org.example.dto.SetmealDto;
import org.example.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @PostMapping("")
    @Transactional()
    public R<String> add(@RequestBody SetmealDto setmealDto){
        log.info("添加套餐，套餐信息：{}",setmealDto.toString());
        setmealService.saveWithDishes(setmealDto);
        return R.success("添加成功！");
    }

    @GetMapping("page")
    public R<Page<SetmealDto>> page(int page, int pageSize, String name){
        Page pageInfo = new Page<>(page, pageSize);

        MPJLambdaWrapper<Setmeal> mpjLambdaWrapper = new MPJLambdaWrapper<>();
        mpjLambdaWrapper.selectAll(Setmeal.class)
                .selectAs(Category::getName,"categoryName")
                .like(StringUtils.isNotEmpty(name),Setmeal::getName,name)
                .orderByAsc(Setmeal::getUpdateTime)
                .leftJoin(Category.class,Category::getId,Setmeal::getCategoryId);
        //NOTE:使用select join maps page可以省去构造dto的过程
        Page page1 = setmealService.selectJoinMapsPage(pageInfo, mpjLambdaWrapper);
        return R.success(page1);
    }

    /**
     *
     * 批量删除
     * @param ids
     * @return
     */
    @DeleteMapping()
    @Transactional
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("删除套餐，ids：{}",ids);
        setmealService.removeWithDishes(ids);
        return R.success("删除成功！");
    }

    /**
     *
     * 修改套餐状态
     * @param status 状态 1启售 0停售
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        log.info("修改套餐状态，ids：{}",ids);
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Setmeal::getStatus,status)
                .in(Setmeal::getId,ids);
        setmealService.update(updateWrapper);
        return R.success("修改成功！");
    }
}
